from typing import List
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select

from app.core.database import get_async_session
from app.core.config import settings
from app.schemas.transcript import Transcript, TranscriptCreate, TranscriptBatch
from app.models.transcript import Transcript as TranscriptModel
from app.models.meeting import Meeting as MeetingModel
from app.models.user import User as UserModel
from app.services.audio import AudioService
from app.services.asr import ASRService

import aiofiles
import os
from pathlib import Path

router = APIRouter()

# 初始化服务
audio_service = AudioService()
asr_service = ASRService()


@router.post("/upload")
async def upload_audio(
    file: UploadFile = File(...),
    meeting_id: int = Form(...),
    current_user: UserModel = None,  # TODO: 添加认证依赖
    db: AsyncSession = Depends(get_async_session)
):
    """上传音频文件"""
    user_id = current_user.id if current_user else 1  # 临时使用固定用户ID

    # 检查会议是否存在且属于当前用户
    meeting_query = select(MeetingModel).where(
        MeetingModel.id == meeting_id,
        MeetingModel.user_id == user_id
    )
    meeting_result = await db.execute(meeting_query)
    meeting = meeting_result.scalar_one_or_none()

    if not meeting:
        raise HTTPException(status_code=404, detail="会议不存在")

    # 验证文件类型
    if not audio_service.is_audio_file(file):
        raise HTTPException(status_code=400, detail="不支持的文件类型")

    # 验证文件大小
    if not await audio_service.validate_file_size(file):
        raise HTTPException(status_code=400, detail="文件大小超出限制")

    try:
        # 保存文件
        file_path = await audio_service.save_uploaded_file(file, meeting_id)

        # 更新会议信息
        meeting.audio_file_path = str(file_path)
        meeting.audio_file_name = file.filename
        meeting.audio_file_size = file.size
        meeting.status = "processing"  # 更新状态为处理中

        await db.commit()

        # TODO: 启动后台任务进行转录
        # background_tasks.add_task(transcribe_audio_task, meeting_id, str(file_path))

        return {
            "message": "文件上传成功",
            "file_path": str(file_path),
            "file_name": file.filename,
            "file_size": file.size
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"文件上传失败: {str(e)}")


@router.get("/transcripts/{meeting_id}", response_model=List[Transcript])
async def get_transcripts(
    meeting_id: int,
    current_user: UserModel = None,  # TODO: 添加认证依赖
    db: AsyncSession = Depends(get_async_session)
):
    """获取会议的转录文本"""
    user_id = current_user.id if current_user else 1  # 临时使用固定用户ID

    # 检查会议是否存在且属于当前用户
    meeting_query = select(MeetingModel).where(
        MeetingModel.id == meeting_id,
        MeetingModel.user_id == user_id
    )
    meeting_result = await db.execute(meeting_query)
    meeting = meeting_result.scalar_one_or_none()

    if not meeting:
        raise HTTPException(status_code=404, detail="会议不存在")

    # 获取转录文本
    query = select(TranscriptModel).where(
        TranscriptModel.meeting_id == meeting_id
    ).order_by(TranscriptModel.timestamp)

    result = await db.execute(query)
    transcripts = result.scalars().all()

    return transcripts


@router.post("/transcripts", response_model=List[Transcript])
async def create_transcripts(
    transcripts: TranscriptBatch,
    current_user: UserModel = None,  # TODO: 添加认证依赖
    db: AsyncSession = Depends(get_async_session)
):
    """批量创建转录文本"""
    user_id = current_user.id if current_user else 1  # 临时使用固定用户ID

    # 验证所有转录文本都属于同一用户的会议
    meeting_ids = list(set(t.meeting_id for t in transcripts.transcripts))
    if len(meeting_ids) > 1:
        raise HTTPException(status_code=400, detail="转录文本必须属于同一会议")

    meeting_id = meeting_ids[0]

    # 检查会议权限
    meeting_query = select(MeetingModel).where(
        MeetingModel.id == meeting_id,
        MeetingModel.user_id == user_id
    )
    meeting_result = await db.execute(meeting_query)
    if not meeting_result.scalar_one_or_none():
        raise HTTPException(status_code=404, detail="会议不存在")

    # 创建转录文本
    db_transcripts = []
    for transcript_data in transcripts.transcripts:
        db_transcript = TranscriptModel(**transcript_data.dict())
        db.add(db_transcript)
        db_transcripts.append(db_transcript)

    await db.commit()

    # 刷新获取ID
    for transcript in db_transcripts:
        await db.refresh(transcript)

    return db_transcripts


@router.post("/transcribe/{meeting_id}")
async def start_transcription(
    meeting_id: int,
    current_user: UserModel = None,  # TODO: 添加认证依赖
    db: AsyncSession = Depends(get_async_session)
):
    """开始音频转录"""
    user_id = current_user.id if current_user else 1  # 临时使用固定用户ID

    # 检查会议是否存在且属于当前用户
    meeting_query = select(MeetingModel).where(
        MeetingModel.id == meeting_id,
        MeetingModel.user_id == user_id
    )
    meeting_result = await db.execute(meeting_query)
    meeting = meeting_result.scalar_one_or_none()

    if not meeting:
        raise HTTPException(status_code=404, detail="会议不存在")

    if not meeting.audio_file_path:
        raise HTTPException(status_code=400, detail="会议没有音频文件")

    try:
        # TODO: 启动转录任务
        # background_tasks.add_task(transcribe_audio_task, meeting_id, meeting.audio_file_path)

        return {
            "message": "转录任务已启动",
            "meeting_id": meeting_id,
            "audio_file": meeting.audio_file_path
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"启动转录失败: {str(e)}")